import {createRouter, createWebHistory} from 'vue-router'
import Layout from '@/layout/index.vue'
import {hasToken} from "@/utils/auth";
import type {RouteRecordRaw} from 'vue-router'
import {useAuthStore} from "@/stores/auth";

export interface RouteMeta {
  tabbar?: {
    show: boolean
    icon?: string
    text?: string
  }
  permissions?: string[]
  role?: string[]
  requiresAuth?: boolean
  tabIndex?: number
}

export type AppRouteRecordRaw = RouteRecordRaw & {
  meta: RouteMeta
}

const routes: any[] = [
  {
    path: '/',
    component: Layout,
    redirect: 'home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/home/home/index.vue'),
        meta: {
          tabbar: {
            show: true,       // 是否显示在底部导航栏
            icon: 'wap-home-o', // 图标名称
            text: '首页',      // 显示文本
          },
          roles: ['student', 'admin']
        }
      },
      {
        path: 'lesson',
        name: 'Lesson',
        component: () => import('@/views/lesson/select-lesson/index.vue'),
        meta: {
          tabbar: {
            show: true,
            icon: 'calendar-o',
            text: '约课',
          },
          roles: ['student', 'admin'],
        },
      },
      {
        path: 'online-practice',
        name: 'OnlinePractice',
        component: () => import('@/views/practice/online-practice/index.vue'),
        meta: {
          tabbar: {
            show: true,
            icon: 'records-o',
            text: '在线练题',
          },
          roles: ['student', 'admin'],
        },
      },
      {
        path: 'personal',
        name: 'PersonalCenter',
        component: () => import('@/views/personal/center/index.vue'),
        meta: {
          tabbar: {
            show: true,
            icon: 'user-o',
            text: '个人中心',
          },
          roles: ['student', 'admin']
        },
      },
    ]
  },
  /* 首页路由*/
  {
    path: '/exam/rule',
    name: 'ExamRule',
    component: () => import('@/views/home/ExamRule/index.vue'),
  },
  {
    path: '/mis/guide',
    name: 'MisGuide',
    component: () => import('@/views/home/MisGuide/index.vue'),
  },
  {
    path: '/activity',
    name: 'ActivityPage',
    component: () => import('@/views/home/ActivityPage/index.vue'),
  },
  {
    path: '/value-added',
    name: 'ValueAddedService',
    component: () => import('@/views/home/ValueAddedService/index.vue'),
  },
  /*课程相关*/
  {
    path: '/lesson/student',
    name: 'StudentLesson',
    component: () => import('@/views/lesson/student-lesson/index.vue'),
  },
  /*练题*/
  {
    path: '/question/sequential-practice',
    name: 'SequentialPractice',
    component: () => import('@/views/practice/sequential-practice/index.vue'),
  },
  {
    path: '/question/ai-practice',
    name: 'AiPractice',
    component: () => import('@/views/practice/ai-practice/index.vue'),
  },
  {
    path: '/question/error-question',
    name: 'ErrorQuestion',
    component: () => import('@/views/practice/error-question/index.vue'),
  },
  {
    path: '/question/classic-question',
    name: 'ClassicQuestion',
    component: () => import('@/views/practice/classic-question/index.vue'),
  },
  {
    path: '/question/special-question',
    name: 'SpecialQuestion',
    component: () => import('@/views/practice/special-question/index.vue'),
  },
  /*个人中心路由*/
  {
    path: '/personal/edit',
    name: 'EditPersonalInfo',
    component: () => import('@/views/personal/EditPersonalInfo/index.vue'),
  },
  {
    path: '/personal/coach',
    name: 'CoachInfo',
    props: (route: any) => ({path: route.query.path}),
    component: () => import('@/views/personal/CoachInfo/index.vue'),
  },
  {
    path: '/personal/update-password',
    name: 'UpdatePassword',
    component: () => import('@/views/personal/update-password/index.vue'),
  },
  {
    path: '/common/problem',
    name: 'CommonProblem',
    component: () => import('@/views/personal/CommonProblem/index.vue'),
  },
  /*系统通用路由*/
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/login/index.vue'),
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register/index.vue'),
  },
  {
    path: '/forget',
    name: 'Forget',
    component: () => import('@/views/auth/ForgetPassword/index.vue'),
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/NotFound/index.vue'),
  },
  {
    path: '/no-permission',
    name: 'NoPermission',
    component: () => import('@/views/error/NoPermission/index.vue'),
    meta: {}
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})


// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 1. 检查是否需要权限校验（meta.roles 或 meta.permissions 存在）
  const authStore = useAuthStore()
  const requiresRoles = to.meta.roles as string[] | undefined
  const requiresPermissions = to.meta.permissions as string[] | undefined

  // 2. 不需要任何校验的路由直接放行
  if (!requiresRoles && !requiresPermissions) {
    return next()
  }

  // 3. 需要校验但未登录的情况
  if (!hasToken()) {
    return next({
      path: '/login',
      query: {redirect: to.fullPath}
    })
  }

  // 4. 获取用户信息（如果未加载）
  if (!authStore.currentUser) {
    try {
      await authStore.setCurrentUser()
    } catch (error) {
      // 获取用户信息失败，清除token并跳转到登录页
      authStore.logout()
      return next({
        path: '/login',
        query: {redirect: to.fullPath}
      })
    }
  }

  // 5. 检查角色权限
  if (requiresRoles && requiresRoles.length > 0) {
    const hasRole = authStore.currentRoles.some(role =>
      requiresRoles.includes(role)
    )

    if (!hasRole) {
      // 角色不匹配，跳转到无权限页面
      return next('/no-permission')
    }
  }

  // 6. 检查操作权限
  if (requiresPermissions && requiresPermissions.length > 0) {
    const hasPermission = authStore.currentPermissions.some(permission =>
      requiresPermissions.includes(permission)
    )

    if (!hasPermission) {
      // 权限不足，跳转到无权限页面
      return next('/no-permission')
    }
  }

  // 7. 已登录且访问登录页，重定向到首页
  if (to.path === '/login') {
    return next('/home')
  }

  // 8. 所有检查通过，允许导航
  next()
})

export default router
